package com.banmao.algorithm.No101To200.No116;

import java.util.ArrayDeque;

public class Solution1 {

    public Node connect(Node root) {

        ArrayDeque<Node> queue = new ArrayDeque<>();
        if(root == null) {
            return null;
        }

        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                Node poll = queue.poll();
                if(i != size - 1) {
                    Node peek = queue.peek();
                    poll.next = peek;
                } else {
                    poll.next = null;
                }

                if(poll.left != null) {
                    queue.add(poll.left);
                }

                if(poll.right != null) {
                    queue.add(poll.right);
                }
            }

        }

        return root;
    }

}

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
}
